﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;
using System.Web.Security;

namespace TireService.Website
{
    public partial class Rabatkode : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["resellerid"] != null)
            {
                try
                {
                    // Login user
                    Guid userid = new Guid(Request.QueryString["resellerid"].ToString());
                    MembershipUser user = Membership.GetUser(userid);
                    FormsAuthentication.SetAuthCookie(user.UserName, false);

                    TireServiceDB db = new TireServiceDB();
                    int CustomerId = db.GetCustomerIdByUserId(userid);

                    // Set session
                    Session["CustomerId"] = CustomerId;

                    Response.Redirect("Kunde/Rabat.aspx");
                }
                catch (Exception ex)
                {
                    // Nothing - error happened
                    string error = ex.Message;
                    //http://localhost:23613/Rabatkode.aspx?resellerid=58a2b128-a2d6-43c5-bd4a-dfd5942fe6e4
                }
            }
        }

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvVoucher_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn Type: NormalPrice
            if (e.Column.FieldName == "NormalPrice")
            {
                // Get unitprice
                if (e.GetListSourceFieldValue("SubscriptionId") != null)
                {
                    TireServiceDB db = new TireServiceDB();

                    string normalprice = string.Format("{0:C}", db.GetSubscriptionPrice(Convert.ToInt32(e.GetListSourceFieldValue("SubscriptionId"))));

                    // Change field value
                    e.Value = normalprice;
                }
                else
                {
                    e.Value = "-";
                }
                
            }
        }

        /// <summary>
        /// Callback function load vouher information in GUI
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void callbackVoucherPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            try
            {
                // Validate voucher / quotation
                string[] param = e.Parameter.Split('-');

                if (param.Count() != 3)
                {
                    // Quotation is not valid
                    throw new ArgumentException("Indtastet rabat-/tilbudskode er ikke gyldig - venligst prøv igen.");
                }

                // Quotation is defined by: QuotationId-CreatedateYear-QuotationCode (ex. 1000-2013-100)
                int QuotationId = Convert.ToInt32(param[0]);
                int DateYear = Convert.ToInt32(param[1]);
                int QuotationCode = Convert.ToInt32(param[2]);

                // Initiate database
                TireServiceDB db = new TireServiceDB();

                // Get quotation
                Quotation quotation = db.GetQuotation(QuotationId, DateYear, QuotationCode);

                if (quotation == null)
                {
                    throw new ArgumentException("Indtastet rabat-/tilbudskode er ikke gyldig - venligst prøv igen.");
                }
                else
                {
                    // Validate if quotation is still active
                    if (quotation.Expiredate <= DateTime.Now)
                    {
                        throw new ArgumentException("Indtastet rabat-/tilbudskode er udløbet - venligst kontakt vores kundesupport.");
                    }
                    if (quotation.Activationdate != null)
                    {
                        throw new ArgumentException("Indtastet rabat-/tilbudskode er allerede brugt.");
                    }
                    if (quotation.ActivationLimit <= quotation.ActivationCount)
                    {
                        throw new ArgumentException("Indtastet rabat-/tilbudskode er udløbet - venligst kontakt vores kundesupport.");
                    }

                    // Get quotation details
                    List<QuotationDetail> quotationdetails = db.GetQuotationDetails(quotation.QuotationId);

                    if (quotationdetails == null)
                    {
                        throw new ArgumentException("Indtastet rabat-/tilbudskode indeholder ingen produkter - venligst kontakt vores kundesupport.");
                    }

                    // Load quotation details into order
                    List<OrderData> customerorders = new List<OrderData>();

                    bool SubscriptionIncluded = false;

                    foreach (QuotationDetail quotationdetail in quotationdetails)
                    {
                        // Create orderline
                        OrderData customerorder = new OrderData();
                        customerorder.SubscriptionId = quotationdetail.SubscriptionId;
                        customerorder.Description = quotationdetail.Description;
                        customerorder.ProductNumber = quotationdetail.ProductNumber;
                        customerorder.Quantity = quotationdetail.Quantity;
                        if (quotation.OneTimeDiscount & quotationdetail.SubscriptionId != null)
                        {
                            customerorder.UnitPrice = db.GetSubscriptionPrice(Convert.ToInt32(quotationdetail.SubscriptionId));
                        }
                        else
                        {
                            customerorder.UnitPrice = quotationdetail.UnitPrice;
                        }
                        customerorder.OneTimeUnitPrice = quotationdetail.UnitPrice;
                        customerorder.TotalPrice = (quotationdetail.Quantity * quotationdetail.UnitPrice);

                        // Check if quotation contains any subscriptions
                        if (quotationdetail.SubscriptionId != null)
                        {
                            SubscriptionIncluded = true;
                        }

                        customerorders.Add(customerorder);
                    }

                    gvVoucher.DataSource = customerorders.ToList();
                    gvVoucher.DataBind();
                }

            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }
    }
}